package com.mhf.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mhf.domain.*;
import com.mhf.feign.MovieFeign;
import com.mhf.mapper.UserMapper;
import com.mhf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private MovieFeign movieFeign;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Movie getById(Long id) {
        return movieFeign.getById(id);
    }

    @Override
    public void buyMovieById(MovieUser movieUser) {
        movieFeign.buyMovie(movieUser);
        //1.获取电影价格，购买张数
        Movie movie = movieFeign.getById(movieUser.getMovieTicketId());
        BigDecimal price = movie.getPrice();
        Long count = movieUser.getCount();
        Long userId = movieUser.getUserId();

        // 获取购买人
        User user = userMapper.getUserById(userId);

        BigDecimal balance = user.getBalance();
        //判断余额是否,余额
        BigDecimal subtract = balance.subtract(price.multiply(BigDecimal.valueOf(count)));
        if(subtract.doubleValue() < 0){
            throw new RuntimeException("余额不足");
        }
        user.setBalance(subtract);
        // 修改用户
        userMapper.update(user);
    }

    /**
     * 通过id，获取电影信息是否过期
     * @param id
     * @return
     */
    @Override
    public OverdueDto overdue(Long id) {
        OverdueDto overdueDto = new OverdueDto();
        //1.获取用户信息
        Object user = movieFeign.getByUserMovie(id).getResultObj();
        MovieUser user1 = JSON.parseObject(JSON.toJSONString(user), MovieUser.class);

        //2.通过用户id获取电影信息
        Movie movie = movieFeign.getById(user1.getMovieTicketId());
        //3.获取当前时间和电影时间进行判断是否过期
        long newDate = new Date().getTime();
        long start = movie.getStart_time().getTime();
        long end = movie.getEnd_time().getTime();
        if (end < newDate){//过期
            overdueDto.setMsg("过期");
            overdueDto.setState("不能使用");
            return overdueDto;
        }else if (start>newDate){
            overdueDto.setMsg("未过期");
            overdueDto.setState("可使用");
            return overdueDto;
        }else {
            overdueDto.setMsg("赶紧的还没结束");
            return overdueDto;
        }
    }
}
